package com.weatherquery.servlet;

import com.weatherquery.informbean.WeatherData;
import com.weatherquery.service.WeatherService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Natural-Pride
 * @Date 2023/12/18 17:18
 * @注释
 */
@WebServlet("/WeatherUpdateServlet")
public class WeatherUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //接收修改后的天气信息
        String cityId = request.getParameter("cityId");
        String city = request.getParameter("city");
        String nowWeather = request.getParameter("nowWeather");
        String nowTemp = request.getParameter("nowTemp");
        String nowWindClass = request.getParameter("nowWindClass");
        String nowWindDir = request.getParameter("nowWindDir");
        String nowUptime = request.getParameter("nowUptime");
        String forecastDate = request.getParameter("forecastDate");
        String forecastWeek = request.getParameter("forecastWeek");
        String forecastWeather = request.getParameter("forecastWeather");
        String forecastHigh = request.getParameter("forecastHigh");
        String forecastLow = request.getParameter("forecastLow");

        // 调用WeatherService执行修改
        WeatherData weatherData = new WeatherData(cityId, city, nowWeather, nowTemp, nowWindClass,
                nowWindDir, nowUptime, forecastDate, forecastWeek, forecastWeather, forecastHigh, forecastLow);
        //创建一个 WeatherService对象
        WeatherService weatherService = new WeatherService();
        //调用 WeatherService的 modifyWeather方法,传入 informBean对象,将返回值赋给 update
        boolean update = weatherService.modifyWeather(weatherData);
        //根据 update的值,设置提示信息
        String tips = update ? "<label style='color:green'>修改成功</label>" : "<label style='color:red'>修改失败</";
        //将 tips保存到 request中
        request.setAttribute("tips", tips);
        //转发请求到 prompt.jsp页面
        request.getRequestDispatcher("prompt.jsp").forward(request, response);
    }

}
